package com.lottery.im.module.main.presenter;

import android.app.Activity;
import android.text.TextUtils;
import com.lottery.im.MyApplication;
import com.lottery.im.api.ApiClient;
import com.lottery.im.api.RetryWithDelay;
import com.lottery.im.api.observer.BaseObserver;
import com.lottery.im.api.result.ApiResult;
import com.lottery.im.api.result.entity.LoginEntity;
import com.lottery.im.api.result.entity.UpdateInfo;
import com.lottery.im.api.result.entity.UserInfo;
import com.lottery.im.api.result.entity.msg_bulletin.MessageCount;
import com.lottery.im.base.BaseFragmentPresenter;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.main.view.HomeView;
import com.lottery.im.util.SPUtils;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.TimeUnit;

public class HomePresenter extends BaseFragmentPresenter<HomeView> {

  public HomePresenter(Activity activity,
      HomeView iView,
      LifecycleProvider<FragmentEvent> provider) {
    super(activity, iView, provider);
  }

  public void refreshUserInfo() {

    if (null == MyApplication.getInstance().getUserInfo()) return;

    String account =
        (String) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.ACCOUNT_KEY, "");
    String pwd = (String) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.PWD_KEY, "");

    if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(pwd)) {
      // 如果保存的账号密码的话，使用登录接口来刷新数据，更准确
      login(account, pwd);
    } else {
      ApiClient.getApiRetrofitInstance()
          .queryUserCommonInfo(MyApplication.getInstance().getUserInfo().getUserId(),
              MyApplication.getInstance().getToken())
          .throttleFirst(2, TimeUnit.SECONDS)
          .retryWhen(new RetryWithDelay(100, 10000))
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .compose(provider.bindToLifecycle())
          .subscribe(new BaseObserver<UserInfo>() {
            @Override public void onStart() {

            }

            @Override public void onSuccess(UserInfo userInfo) {
              iView.refreshUserInfoSuc(userInfo);
            }

            @Override public void onFail(String code, String msg) {

            }

            @Override public void onException(String msg) {

            }

            @Override public void onFinish() {

            }
          });
    }
  }

  private void login(String account, String pwd) {

    ApiClient.getApiRetrofitInstance()
        .login(account, pwd, "Android")
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(provider.bindToLifecycle())
        .subscribe(new BaseObserver<LoginEntity>() {
          @Override public void onStart() {

          }

          @Override public void onSuccess(LoginEntity loginEntity) {
            iView.loginSuccess(loginEntity);
          }

          @Override public void onFail(String code, String msg) {

          }

          @Override public void onException(String msg) {

          }

          @Override public void onFinish() {

          }
        });
  }

  /**
   * 检测更新
   */
  public void queryAppUpdateInfo() {
    ApiClient.getApiRetrofitInstance()
        .queryAppUpdateInfo("ANDROID")
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(provider.bindToLifecycle())
        .subscribe(new BaseObserver<UpdateInfo>() {
          @Override public void onStart() {
          }

          @Override public void onSuccess(UpdateInfo info) {
            iView.querySuccess(info);
          }

          @Override public void onFail(String code, String msg) {
          }

          @Override public void onException(String msg) {

          }

          @Override public void onFinish() {

          }
        });
  }

  public void queryUserSystemMessageCount(){

    ApiClient.getApiRetrofitInstance()
        .queryUserSystemMessageCount(MyApplication.getInstance().getUserInfo().getUserId(),
            MyApplication.getInstance().getToken())
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<ApiResult<MessageCount>>() {
          @Override public void onSubscribe(Disposable disposable) {

          }

          @Override public void onNext(ApiResult<MessageCount> messageCountApiResult) {
            iView.queryMessageCountResult(messageCountApiResult);
          }

          @Override public void onError(Throwable throwable) {

          }

          @Override public void onComplete() {

          }
        });
  }
}
